package com.suirich.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suirich.bean.HomeAd;
import com.suirich.common.Constants;
import com.suirich.service.HomeAdService;

@Controller
@RequestMapping("/advertisement")
public class AdvertisementController {
	@Autowired
	private HomeAdService homeAdService;
	
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> create(HomeAd homeAd) {

        Map<String,String> result = new HashMap<String,String>();
        
		try {
			HomeAd ad = new HomeAd();
			ad.setPosition(homeAd.getPosition());
			
			List<HomeAd> homeAdList = this.homeAdService.read(ad);
			
			homeAd.setCreateDate(new Date());
			
			if(CollectionUtils.isNotEmpty(homeAdList) && homeAdList.size()>0){
				HomeAd hAd = homeAdList.get(0);
				hAd.setImagePath(homeAd.getImagePath());
				hAd.setLink(homeAd.getLink());
				hAd.setCreateDate(homeAd.getCreateDate());
				this.homeAdService.update(hAd);
			}else{
				this.homeAdService.create(homeAd);
			}
			
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
		} catch (Exception e) {
			
            result.put("result", Constants.FAILURE_RESULT_FLAG);
		}

        return result;
    }
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> list(HomeAd homeAd) {
        Map<String,Object> result = new HashMap<String,Object>();
        
        try {
            List<HomeAd> homeAdList = this.homeAdService.read(homeAd);

            result.put("homeAdList", homeAdList);
            result.put("result", Constants.SUCCESS_RESULT_FLAG);
        } catch (Exception e) {
            
            result.put("result", Constants.FAILURE_RESULT_FLAG);
        }
        

        return result;
    }
}
